package com.itheima.web.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@WebServlet("/req2")
public class RequestDemo2  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 测试Get读取
        req.setCharacterEncoding("utf-8"); // 对Get请求不起作用
        String user = req.getParameter("username");
        String utfUser = new String(user.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(user);
        System.out.println(utfUser);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 测试Post读取
        // 读取所有数据
//        Map<String, String[]> allData = req.getParameterMap();
//        System.out.println(allData.get("username")[0]);
//        System.out.println(allData.get("password")[0]);
//        String[] likes = allData.get("hobby");
//        for (String like:likes) {
//            System.out.println(like);
//        }
        // 一般就是通以下2方式最多
        // 读取单个
        req.setCharacterEncoding("utf-8");
        String user = req.getParameter("username");
        String pass = req.getParameter("password");
        System.out.println("单独user:"+user);
        System.out.println("单独password:"+pass);
        // 非常确定一个名字，对应多个值
        String[] hobbys = req.getParameterValues("hobby");
        for (String hobby:hobbys) {
            System.out.println(hobby);
        }
    }
}
